package utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期转换工具
 * Created by weijianyu on 2017/4/23.
 */
public class DateUtil {
    private static final Logger logger = LogManager.getLogger(DateUtil.class);

    public static final String TOYEAR = "yyyy";
    public static final String TOMONTH = "yyyy-MM";
    public static final String TODAY = "yyyy-MM-dd";
    public static final String TOSECOND = "yyyy-MM-dd HH:mm:ss";

    private DateUtil() {

    }

    /**
     * 日期格式转换成字符串格式
     *
     * @param date    日期格式
     * @param pattern 转换格式
     * @return 字符串格式
     */
    public static String date2String(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    /**
     * 字符串格式转换成日期格式
     *
     * @param date    字符串格式日期
     * @param pattern 转换格式
     * @return 日期格式时间
     */
    public static Date string2Date(String date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date result = null;
        try {
            result = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            logger.error("日期转换错误", e);
        }
        return result;
    }

    /**
     * 获取当前时间到未来某几天
     * @param past 未来天数
     * @return 未来的时间
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(TOSECOND);
        return format.format(today);
    }

}
